from django.db import models
from django.contrib.auth import get_user_model
from django.utils import timezone

User = get_user_model()


class KnowledgeBase(models.Model):
    """知识库"""
    STATUS_CHOICES = [
        ('private', '私有'),
        ('shared', '共享'),
        ('public', '公开')
    ]
    
    name = models.CharField(max_length=200, verbose_name="知识库名称")
    description = models.TextField(blank=True, verbose_name="描述")
    
    # 关联
    owner = models.ForeignKey(User, on_delete=models.CASCADE, related_name='knowledge_bases', verbose_name="所有者")
    
    # 设置
    status = models.CharField(max_length=20, choices=STATUS_CHOICES, default='private', verbose_name="状态")
    tags = models.JSONField(default=list, verbose_name="标签")
    
    # 统计
    document_count = models.PositiveIntegerField(default=0, verbose_name="文档数量")
    total_size = models.BigIntegerField(default=0, verbose_name="总大小(字节)")
    
    created_at = models.DateTimeField(default=timezone.now, verbose_name="创建时间")
    updated_at = models.DateTimeField(auto_now=True, verbose_name="更新时间")

    class Meta:
        verbose_name = "知识库"
        verbose_name_plural = "知识库"
        db_table = 'knowledge_base'
        ordering = ['-created_at']

    def __str__(self):
        return self.name


class Document(models.Model):
    """文档"""
    DOCUMENT_TYPE_CHOICES = [
        ('text', '文本'),
        ('markdown', 'Markdown'),
        ('pdf', 'PDF'),
        ('word', 'Word文档'),
        ('web', '网页'),
        ('video', '视频'),
        ('audio', '音频')
    ]
    
    STATUS_CHOICES = [
        ('uploading', '上传中'),
        ('processing', '处理中'),
        ('ready', '就绪'),
        ('error', '错误')
    ]
    
    knowledge_base = models.ForeignKey(KnowledgeBase, on_delete=models.CASCADE, related_name='documents')
    title = models.CharField(max_length=300, verbose_name="文档标题")
    content = models.TextField(blank=True, verbose_name="文档内容")
    
    # 文件信息
    document_type = models.CharField(max_length=20, choices=DOCUMENT_TYPE_CHOICES, verbose_name="文档类型")
    file_path = models.CharField(max_length=500, blank=True, null=True, verbose_name="文件路径")
    file_size = models.BigIntegerField(default=0, verbose_name="文件大小")
    file_hash = models.CharField(max_length=64, blank=True, verbose_name="文件哈希")
    
    # 元数据
    author = models.CharField(max_length=100, blank=True, verbose_name="作者")
    source_url = models.URLField(blank=True, null=True, verbose_name="来源链接")
    metadata = models.JSONField(default=dict, verbose_name="元数据")
    
    # 状态
    status = models.CharField(max_length=20, choices=STATUS_CHOICES, default='uploading', verbose_name="状态")
    is_indexed = models.BooleanField(default=False, verbose_name="是否已索引")
    
    # 统计
    view_count = models.PositiveIntegerField(default=0, verbose_name="查看次数")
    reference_count = models.PositiveIntegerField(default=0, verbose_name="引用次数")
    
    created_at = models.DateTimeField(default=timezone.now, verbose_name="创建时间")
    updated_at = models.DateTimeField(auto_now=True, verbose_name="更新时间")
    indexed_at = models.DateTimeField(blank=True, null=True, verbose_name="索引时间")

    class Meta:
        verbose_name = "文档"
        verbose_name_plural = "文档"
        db_table = 'knowledge_document'
        ordering = ['-created_at']

    def __str__(self):
        return self.title


class DocumentChunk(models.Model):
    """文档分块"""
    document = models.ForeignKey(Document, on_delete=models.CASCADE, related_name='chunks')
    content = models.TextField(verbose_name="分块内容")
    
    # 分块信息
    chunk_index = models.PositiveIntegerField(verbose_name="分块索引")
    start_position = models.PositiveIntegerField(verbose_name="开始位置")
    end_position = models.PositiveIntegerField(verbose_name="结束位置")
    
    # 向量嵌入
    embedding = models.JSONField(blank=True, null=True, verbose_name="向量嵌入")
    embedding_model = models.CharField(max_length=100, blank=True, verbose_name="嵌入模型")
    
    created_at = models.DateTimeField(default=timezone.now, verbose_name="创建时间")

    class Meta:
        verbose_name = "文档分块"
        verbose_name_plural = "文档分块"
        db_table = 'knowledge_document_chunk'
        ordering = ['document', 'chunk_index']

    def __str__(self):
        return f"{self.document.title} - 分块{self.chunk_index}"


class KnowledgeTag(models.Model):
    """知识标签"""
    name = models.CharField(max_length=50, unique=True, verbose_name="标签名称")
    description = models.TextField(blank=True, verbose_name="标签描述")
    color = models.CharField(max_length=7, default='#007bff', verbose_name="标签颜色")
    
    # 统计
    usage_count = models.PositiveIntegerField(default=0, verbose_name="使用次数")
    
    created_at = models.DateTimeField(default=timezone.now, verbose_name="创建时间")

    class Meta:
        verbose_name = "知识标签"
        verbose_name_plural = "知识标签"
        db_table = 'knowledge_tag'
        ordering = ['name']

    def __str__(self):
        return self.name


class SearchHistory(models.Model):
    """搜索历史"""
    user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='search_history')
    knowledge_base = models.ForeignKey(KnowledgeBase, on_delete=models.CASCADE, blank=True, null=True)
    
    query = models.CharField(max_length=500, verbose_name="搜索查询")
    results_count = models.PositiveIntegerField(default=0, verbose_name="结果数量")
    
    created_at = models.DateTimeField(default=timezone.now, verbose_name="创建时间")

    class Meta:
        verbose_name = "搜索历史"
        verbose_name_plural = "搜索历史"
        db_table = 'knowledge_search_history'
        ordering = ['-created_at']

    def __str__(self):
        return f"{self.user.username}: {self.query}"


class Annotation(models.Model):
    """文档标注"""
    ANNOTATION_TYPE_CHOICES = [
        ('highlight', '高亮'),
        ('note', '笔记'),
        ('bookmark', '书签'),
        ('comment', '评论')
    ]
    
    document = models.ForeignKey(Document, on_delete=models.CASCADE, related_name='annotations')
    user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='annotations')
    
    annotation_type = models.CharField(max_length=20, choices=ANNOTATION_TYPE_CHOICES, verbose_name="标注类型")
    content = models.TextField(verbose_name="标注内容")
    
    # 位置信息
    start_position = models.PositiveIntegerField(verbose_name="开始位置")
    end_position = models.PositiveIntegerField(verbose_name="结束位置")
    selected_text = models.TextField(blank=True, verbose_name="选中文本")
    
    # 样式
    color = models.CharField(max_length=7, default='#ffff00', verbose_name="颜色")
    
    created_at = models.DateTimeField(default=timezone.now, verbose_name="创建时间")
    updated_at = models.DateTimeField(auto_now=True, verbose_name="更新时间")

    class Meta:
        verbose_name = "文档标注"
        verbose_name_plural = "文档标注"
        db_table = 'knowledge_annotation'
        ordering = ['-created_at']

    def __str__(self):
        return f"{self.user.username} - {self.document.title}: {self.annotation_type}"